<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="width" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="menuForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { inputFormSchemas } from './data';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { listLogEvent, saveOrUpdateLogEvent } from './api';
import { useAdapt } from '/@/hooks/system/useAutoAdapt';
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();
const emit = defineEmits(['success', 'register']);
const { width } = useAdapt({ xl: 600, lg: 600, md: 600, sm: 600, xs: 600})
const attrs = useAttrs()
const isUpdate = ref(true);
const parentKey = ref("0");

const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
  labelWidth: 80,
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 20 },
  },
  schemas: inputFormSchemas,
  showActionButtonGroup: false
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields()
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  parentKey.value = data?.record?.parentKey;

  updateSchema([
    {
      field: 'parentKey',
      componentProps: { 
        optionFilterProp: "label",
        showSearch: true,
        labelField: 'eventValue',
        valueField: 'eventKey',
        api: listLogEvent,
        immediate: true,
      },
    }
  ]);

  if (typeof data.record === 'object') {
    let values = { ...data.record }
    setFieldsValue(values)
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增日志事件' : '编辑日志事件'));

async function handleSubmit() {
  try {
    const values = await validate()
    console.log("submit menu: ", values);

    if (isUpdate.value && values.parentKey === values.eventKey) {
      createMessage.error('上级不能选择自己')
      return
    }

    setDrawerProps({ confirmLoading: true });
    await saveOrUpdateLogEvent({ ...values }, unref(isUpdate));
    closeDrawer();
    createMessage.success(`${getTitle.value}成功`)
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
